package com.abner.juc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 题目：现在两个线程，可以操作初始值为零的一个变量，
 * 实现一个线程对该变量加1，一个线程对该变量-1，
 * 实现交替，来10轮，变量初始值为0.
 *      1.高内聚低耦合前提下，线程操作资源类
 *      2.判断/干活/通知
 *      3.防止虚假唤醒(判断只能用while，不能用if)
 * 知识小总结：多线程编程套路+while判断+新版写法
 * @author Abner
 */
public class ProducerConsumer {
    public static void main(String[] args) {
        AirConditioning airConditioning = new AirConditioning();
        new Thread(() -> { for (int i = 0;i < 10; i++) airConditioning.decrement();},"a").start();
        new Thread(() -> { for (int i = 0;i < 10; i++) airConditioning.decrement();},"b").start();
        new Thread(() -> { for (int i = 0;i < 10; i++) airConditioning.decrement();},"c").start();
        new Thread(() -> { for (int i = 0;i < 10; i++) airConditioning.decrement();},"d").start();
    }
}


class AirConditioning {

    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            while(num != 0) {
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"\t"+num);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            while(num == 0) {
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"\t"+num);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 老版写法
     */
//    public synchronized void decrement() throws InterruptedException {
//        while (num == 0) {
//            this.wait();
//        }
//        num--;
//        System.out.println(Thread.currentThread().getName()+"\t"+num);
//        this.notifyAll();
//    }
}